package com.onec.service.netty.ssl;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.ssl.SslHandler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;

public class SecureChatServer {


  class secureChatServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
      ChannelPipeline pipeline = ch.pipeline();
      SSLContext sslContext = SSLContext.getDefault();

      SSLEngine sslEngine = sslContext.createSSLEngine();
      sslEngine.setNeedClientAuth(false);
      sslEngine.setUseClientMode(false);

      ChannelHandler handler = new SslHandler(sslEngine);
      pipeline.addLast(handler);

      ChannelPipeline channelPipeline = pipeline
          .addLast("framer",
              new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));

      pipeline.addLast(new StringDecoder());
      pipeline.addLast(new StringEncoder());

      // 业务处理器
      //pipeline.addLast();
    }
  }

  class ClientTest {

    public void start() {

      EventLoopGroup eventExecutors = new NioEventLoopGroup();

      Bootstrap bootstrap = new Bootstrap();
      bootstrap.group(eventExecutors);
      bootstrap.channel(NioSocketChannel.class);
      // 业务处理
//      bootstrap.handler();
      try {
        Channel channel = bootstrap.connect().sync().channel();
        ChannelFuture channelFuture = null;

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        for (; ; ) {
          String line = bufferedReader.readLine();
          if (null != line) {
            channelFuture = channel.writeAndFlush(line + "\r\n");

          }
          if ("bye".equalsIgnoreCase(line)) {
            channel.closeFuture().sync();
            break;
          }
        }

      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }

    }
  }
}
